const { app, BrowserWindow, ipcMain, Menu, webContents, screen, dialog } = require('electron');
const fs = require('fs');

const path = require('node:path');

const { Console } = require('node:console');
const { permission } = require('node:process');
const storagePath = path.join(app.getPath('userData'), 'storage.json');
console.log('=============>', storagePath);

let mainWindow;

let hid_device = null;
const vendorId = 0xA8A4;
const productId = 0x2255;
const interfaceId = 2;
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
// if (require('electron-squirrel-startup')) {
//   app.quit();
// }

const createWindow = () => {
  // Create the browser window.
  const primaryDisplay = screen.getPrimaryDisplay();
  const { width, height } = primaryDisplay.workAreaSize; // 可用区域大小（除去 dock、任务栏）
  console.log(`Screen width: ${width}`);
  console.log(`Screen height: ${height}`);
  mainWindow = new BrowserWindow({
    // fullscreen: true,            // ✅ 添加此行：启动时直接全屏
    x: 0,
    y: 0,
    width: width * 4 / 8,
    // width: width,
    height: height,
    resizable: true,
    backgroundColor: '#000000',
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      devTools: true,  // 禁用开发者工具
    },
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'html/index.html'));
  // mainWindow.loadFile(path.join(__dirname, 'html/preImage.html'));
  // Open the DevTools.
  mainWindow.webContents.openDevTools();
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow();
  // 禁用菜单栏
  Menu.setApplicationMenu(null);
  supportWebHid();
  handleActions();

  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 程序退出时停止监听
process.on('exit', () => {
});

function handleActions() {
  console.log('开始初始化接口');
  // ipcMain.handle('get-hid-list', HIDList);
  // ipcMain.on('open-hid', openHID);
  // ipcMain.on('send-data', sendData);
  ipcMain.handle('save-file', saveFile);
  ipcMain.handle('open-file', readFile);
  ipcMain.handle('set-key-value', setItem);
  ipcMain.handle('get-key-value', getItem);
}

///webhid 授权配置
function supportWebHid() {
  mainWindow.webContents.session.on('select-hid-device', (event, details, callback) => {
    // Add events to handle devices being added or removed before the callback on
    // `select-hid-device` is called.
    mainWindow.webContents.session.on('hid-device-added', (event, device) => {
      console.log('hid-device-added FIRED WITH', device)
      // Optionally update details.deviceList
    })

    mainWindow.webContents.session.on('hid-device-removed', (event, device) => {
      console.log('hid-device-removed FIRED WITH', device)
      // Optionally update details.deviceList
    })

    event.preventDefault()
    if (details.deviceList && details.deviceList.length > 0) {
      callback(details.deviceList[0].deviceId)
    }
  })


  mainWindow.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
    if (permission === 'hid' && details.securityOrigin === 'file:///') {
      return true
    }
  })

  mainWindow.webContents.session.setDevicePermissionHandler((details) => {
    if (details.deviceType === 'hid' && details.origin === 'file://') {
      return true
    }
  })
}

///保存文件
async function saveFile(event, { defaultFileName, defaultFileExt, content }) {
  try {
    // 弹出保存对话框
    const { filePath } = await dialog.showSaveDialog({
      title: 'Save to file',
      defaultPath: `${defaultFileName}${defaultFileExt}`,
      filters: [
        { name: 'Text Files', extensions: ['DSP'] },
        // { name: 'JSON Files', extensions: ['json'] },
        // { name: 'All Files', extensions: ['*'] }
      ]
    });

    if (!filePath) return { success: false, error: '用户取消保存' };

    // 写入文件
    await fs.promises.writeFile(filePath, content);
    return { success: true, path: filePath };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

///读取文件
async function readFile(event) {
  try {
    const { filePaths } = await dialog.showOpenDialog({
      title: 'Choose file',
      filters: [
        { name: 'Text Files', extensions: ['DSP'] },
      ],
      properties: ['openFile']
    });

    if (!filePaths || filePaths.length === 0) {
      return { success: false, error: 'User cancelled file selection' }; // 明确错误信息
    }

    const filePath = filePaths[0];
    const content = await fs.promises.readFile(filePath, 'utf-8');
    return { success: true, path: filePath, content };
  } catch (error) {
    console.error('File read error:', error.message);
    return { success: false, error: error.message || 'Unknown error occurred' }; // 防止 undefined
  }
}

function setItem(event, key, value) {
  const data = fs.existsSync(storagePath) ?
    JSON.parse(fs.readFileSync(storagePath)) : {};
  data[key] = value;
  fs.writeFileSync(storagePath, JSON.stringify(data));
}

function getItem(event, key) {
  const data = fs.existsSync(storagePath) ? JSON.parse(fs.readFileSync(storagePath)) : {};
  return data[key] || '';
}
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
